package com.dysjsjy.java.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.dysjsjy.java.common.Result;
import com.dysjsjy.java.entity.User;
import com.dysjsjy.java.mapper.UserMapper;
import com.dysjsjy.java.utils.AliUploadUtils;
import com.dysjsjy.java.utils.UserUtils;

import java.util.Random;

@RequestMapping("/system")
@RestController
@Slf4j
@RequiredArgsConstructor
public class SystemController {

    private final AliUploadUtils aliUploadUtils;

    private final UserMapper userMapper;

    @Value("${ali-oss.domain}")
    private String domain;

    /**
     * 更新头像
     * @param file
     * @return
     */
    @PostMapping(value = "/uploadImg")
    public Result uploadImg(@RequestBody MultipartFile file){
        String newFileName = generateRandomString();
        String url = aliUploadUtils.uploadFile(file, "link", newFileName+".jpg", true);
        User user = userMapper.selectOne(new QueryWrapper<User>().lambda().eq(User::getId, UserUtils.getCurrentLoginId()));
        user.setAvatar(domain+url);
        userMapper.update(user, new QueryWrapper<User>().lambda().eq(User::getId, UserUtils.getCurrentLoginId()));
        return Result.data(domain + url);
    }

    /**
     * 纯上传图片
     * @param file
     * @return
     */
    @PostMapping(value = "/uploadImg2")
    public Result uploadImg2(@RequestBody MultipartFile file){
        String newFileName = generateRandomString();
        String url = aliUploadUtils.uploadFile(file, "link", newFileName+".jpg", true);
        return Result.data(domain + url);
    }

    private String generateRandomString() {
        String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        int STRING_LENGTH = 12;
        Random random = new Random();
        StringBuilder sb = new StringBuilder(STRING_LENGTH);
        for (int i = 0; i < STRING_LENGTH; i++) {
            int index = random.nextInt(CHARACTERS.length());
            sb.append(CHARACTERS.charAt(index));
        }
        return sb.toString();
    }
}
